package com.sgai.zero_robot.ui.alarm;

import static com.sgai.zero_robot.utils.LogUtil.rootPath;

import com.google.gson.Gson;
import com.sgai.zero_robot.pojo.AlarmInfo;
import com.sgai.zero_robot.ui.history.RunnableCallBack;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LoadAlarmRunnable implements Runnable {
    private final RunnableCallBack<List<AlarmInfo>> callBack;
    private BufferedReader br;

    public LoadAlarmRunnable(RunnableCallBack<List<AlarmInfo>> callBack) {
        this.callBack = callBack;
    }

    @Override
    public void run() {
        File file = new File(rootPath + "/alarm/");
        if (!file.exists()) {
            file.mkdirs();
        } else if (!file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        File[] files = file.listFiles();
        if (files.length <= 0) {
            if (callBack != null) {
                callBack.onResult(new ArrayList<>());
            }
        } else {
            List<AlarmInfo> alarmInfos = new ArrayList<>();
            try {
                for (int i = 0; i < files.length; i++) {
                    File alarmFile = files[i];
                    Gson gson = new Gson();
                    FileInputStream fis = new FileInputStream(alarmFile);
                    InputStreamReader isr = new InputStreamReader(fis);
                    br = new BufferedReader(isr);

                    String line;
                    while ((line = br.readLine()) != null) {
                        AlarmInfo alarmInfo = gson.fromJson(line, AlarmInfo.class);
                        if (alarmInfo!=null){
                            alarmInfos.add(alarmInfo);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e) {

                }
                Collections.sort(alarmInfos, (o1, o2) -> Long.compare(o2.getTime(), o1.getTime()));
                if (callBack != null) {
                    callBack.onResult(alarmInfos);
                }
            }
        }
    }
}